import { Card, Form, Input, Checkbox, Button, message } from 'antd'
import { useNavigate } from 'react-router-dom'
import logo from '@/assets/logo.png'
// 导入登录样式
import './index.scss'
// 引入useStore
import useStore from '@/store'

function Login() {
  const { loginStore } = useStore() // 解构出来 loginStore
  const navigate = useNavigate() // 编程式路由跳转
  async function onFinish(value) {
    // value是当前表单输入的所有数据
    // 调用 loginStore 中的 getToken
    await loginStore.getToken({
      mobile: value.username,
      code: value.password,
    })
    // 跳转到首页
    navigate('/', { replace: true })
    // 提示用户登录成功
    message.success('登录成功')
  }

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        {/* 子项用到的触发事件 需要在Form中都声明一下才可以 */}
        <Form
          validateTrigger={['onBlur', 'onChange']}
          initialValues={{
            remember: true,
            password: '246810',
            username: '18866665555',
          }}
          autoComplete="off"
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: '请输入手机号!',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur',
              },
            ]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码!',
              },
              { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
            ]}
          >
            <Input size="large" placeholder="请输入密码" />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked">
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
